<?php
namespace User\Controller;
use Think\Controller;
use Think\Crypt;
use Org\Net;
/**
 * 会员
 */
class LoginController extends Controller {
    
    /**
     * [index  会员默认登陆页面]
     * @return [type] [description]
     */
    public function index()
    {
      if(session('user.id')){
         $this->redirect('index/index');
      }
      $this->display();
    }
    

    //微信登陆处理
    public function login_s()
    {
        $data=I("post.");
        $rules =array(
         array('user_tel','/^1[3|4|5|7|8][0-9]\d{8}$/','手机号码错误！','0','regex',1),
         array('password','require','密码必须填写！'),
         );
        $user=M("user");
        if (!$user->validate($rules)->create()){
            $this->error($user->getError());
        }else{
            $_user=$user->where(array("user_tel"=>$data['user_tel'], "password"=>md5($data['password'])))->find();
            if(!$_user){
                $this->error("账号或密码错误!");
                die();
            }
            $this->update_user($_user['id']); //更新登陆地址和登陆时间
            session('user.user_tel',en_crypt($_user['user_tel']));
            session('user.id',en_crypt($_user['id']));
            $this->success("登陆成功!",U('index/index'));
        }
    }


    /**
     * [reg 注册页面]
     * @return [type] [description]
     */
    public function reg()
    {   
        $uid=I('get.uid')?I('get.uid'):0;
        cookie("user_pid",$uid);
        $uid= de_crypt($uid); //解密
        $data['uid']=$uid;
        $data['title']="会员注册";
        $this->assign($data);
        $this->display();
    }
    

   public function js()
   {
      $code=I('get.code');
      $uid= de_crypt($code); //解密
      echo $uid;
   }


    /**
     * [reg_s  注册处理]
     * $ajax   get的AJAX存在返回ajax数据
     * @return [type] [description]
     */
    public function reg_s()
    {   
        $ajax=(int)I('get.ajax');
        $data=I("post.");
        unset($data['Captcha']);
        $user = D("user"); // 实例化User对象 // 手动进行令牌验证 
        if (!$user->create()){
            $this->error($user->getError());
        }
       if(C("MSG_STATE")){
         if(empty($data['code'])){
            $this->error("验证码必须填写!");
         }
         if($data['code']!==cookie("code") || $data['user_tel']!==cookie("sms_user_tel")){
            $this->error("验证码不正确!");
         }  
        }
        unset($data['user_tel2']);
        $data['reg_ip']=iplong(get_ip());
        $data['reg_time']=time();
        $data["password"]=md5($data["password"]);
        $data['user_pid']=cookie("user_pid")?de_crypt(cookie("user_pid")):0;
        //注册就送
        if(C("REG_MONEY")){
          $data["balance"]=C('REG_MONEY');
        }
        if($uid=$user->add($data)){ 
             $this->update_user($uid); //更新登陆IP 和 登陆时间
             //加款日志
             if(C('REG_MONEY')){
             $jiakuan_data=array(
                 "uid"=>$uid,
                 'time'=>time(),
                 'price'=>C('REG_MONEY'),
                 'type'=> 1,
                 'info' =>'注册就送活动.',
             );
             M("jiakuan_log")->add($jiakuan_data);
             }
			 //if($data['user_pid']){
				//上级收益
			//	$this->invited_jifei($data['user_pid']);
			 //}
             session('user.user_tel',en_crypt($data['user_tel']));
             session('user.id',en_crypt($uid));
             $this->success("恭喜您!注册成功!",U('Index/index'));
        }else{ 
           $this->error("注册失败!请联系管理员...");
        }
    }
    
    /**
     * [update_user   封装用户邀请,上级计费]
     * @return [bool] [更新成功返回真]
     */
    private function invited_jifei($user_pid){
        if ($user_pid){
	$user_model = M('user');
        $user = $user_model->field('id','user_pid')->where("id=".$user_pid)->find();
            //邀请费用
            $invited_price = C('INVITED_PRICE');
			$user_model->where("id=".$user_pid)->setField(array(
				"balance" =>array('exp','balance+'.$invited_price),
				"totle_yq"=>array('exp','totle_yq+'.$invited_price), //邀请总额+本次邀请带来的收益
			));
			//加款日志
			$jiakuan_data=array(
				"uid"=>$user_pid,
				'time'=>time(),
				'price'=>$invited_price,
				'type'=> 3,
				'info' =>'邀请注册加款.',
			);
			M("jiakuan_log")->add($jiakuan_data);
			/*添加计费总表（每日开销）*/
			//今日0点0分0秒
			$time = strtotime(date('Y-m-d',time()));
			$M=M("time_jifei_ip");
			if(!$M->where(array("time"=>$time))->find()){
			 $data=array(
			   "time"=>$time,
				'price'=>$invited_price
				);
			  $M->add($data);
			}else{
			 $s= $M->where(array("time"=>$time))->setInc('price',$invited_price);

			}
			//$s= M("time_jifei_ip")->where(array("time"=>$time))->setInc('price',$invited_price);
		}
    }

    /**
     * [update_user   封装更新用户登陆时间和IP动作]
     * @return [bool] [更新成功返回真]
     */
    private function update_user($uid)
    {
        if(!$uid){ return false;}
        $data=array(
          'login_ip'=>iplong(get_ip()),
          "login_time"=>time(),
            );
        if(M('user')->where("id=".$uid)->save($data)!==false){ 
           return true;
        }else{ 
           return false;
        }
    }
    

     /**
     * [update_user   封装更新用户头像和昵称]
     * @return [bool] [更新成功返回真]
     * $opeb_id 如果为真更新open_id;
     */
    private function update_user_weixin($uid,$data,$open_id=null)
    {
        if(!$uid){ return false;}
        $weixin_data=array(
          'nickname'=>$data['nickname'],
          "avatar"=>$data['avatar'],
          'look'=>$data['subscribe'],
            );
        if($open_id){ 
           $weixin_data['open_id']=$data['open_id'];
        }
        if(M('user')->where("id=".$uid)->save($weixin_data)!==false){ 
           return true;
        }else{ 
           return false;
        }
    }
 

    //封装微信登陆方法
    private function weixin_auth()
    { 
     import("Lib.Weixin.Wxauth");
     $options = array(
        'token'=>'tokenaccesskey', //填写你设定的key
        'appid'=>C('APPID'), //填写高级调用功能的app id, 请在微信开发模式后台查询
        'appsecret'=>C('APPSECRET'), //填写高级调用功能的密钥
     );
     $UserInfo= new \Wxauth($options);
     return $UserInfo;
    }
    
    public function weixin2()
    {
     //$data=file_get_contents("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx05c6c0bd21cd1976&redirect_uri=http://www.3045.com.cn/user/login/weixin2&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect");
     P(I('get.'));die;
    }    

    //微信登陆
    public function weixin()
    {  
       $data=$this->weixin_auth();
       $user=$data->wxuser;
       if(empty($user)){
         $this->error("微信信息获取失败!");
         $this->redirect('/User');
       }
       $user['nickname']=preg_replace('/[\x{10000}-\x{10FFFF}]/u','',$user['nickname']);
       $user['subscribe']= empty($user['subscribe']) ? 0 :$user['subscribe'];
       $w_user=M("user")->where(array("open_id"=>$user['open_id']))->find();
       if($w_user && $user){ 
          $this->update_user($w_user['id']); //更新登陆时间和IP
          $this->update_user_weixin($w_user['id'],$user,false); //更新头像和昵称
          session("user.look",$user['subscribe']);
          session('user.id',en_crypt($w_user['id']));
       }else{
          $user_tel=session('user.user_tel');
          $user_id=session('user.id');
          //查询是不是注册好的手机用户,没有绑定微信
          if(isset($user_tel) && isset($user_id))
          {
              //已绑定用户,更新微信open_id/
              $user_id=de_crypt($user_id);
              $this->update_user_weixin($user_id,$user,true); //更新微信open_id
              session("user.look",$user['subscribe']);
              session('user.id',en_crypt($user_id));
          }else{
              //都没有情况下新建账号
              $data=array(
                 'open_id'=>$user['open_id'],
                 'nickname'=>$user['nickname'],
                 'look'=>$user['subscribe'],
                 'avatar'=>$user['avatar'],
                 'reg_ip'=>iplong(get_ip()),
                 "reg_time"=>time(),
                );
              $data['nickname']=preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $data['nickname']);
              //注册就送
              if(C("REG_MONEY")){
                $data["balance"]=C('REG_MONEY');
              }
              //获取推广会员的IP user_pid
              if(cookie("user_pid"))
              {
                 $data['user_pid']=de_crypt(cookie("user_pid"));
              }
              $uid = M('user')->add($data);
              if(C('REG_MONEY')){
               $jiakuan_data=array(
                 "uid"=>$uid,
                 'time'=>time(),
                 'price'=>C('REG_MONEY'),
                 'type'=> 1,
                 'info' =>'注册就送活动.',
               );
               M("jiakuan_log")->add($jiakuan_data);
              }
			  //if($data['user_pid']){
				//上级收益
			//	$this->invited_jifei($data['user_pid']);
			// }
              $this->update_user($uid); //更新登陆时间和IP
              session("user.look",$user['subscribe']);
              session('user.id',en_crypt($uid));
          }
       }
       if(I('get.jh'))
       {   
           cookie("jh",'true');
           if(!$user['subscribe']){
              $this->error("亲!不要偷懒哦!关注我们公众号才可以激活哦!",U("/Article/weixin/"));
           }
       }
       if(cookie("jh")){
          cookie("jh",null);
          $this->success("激活成功!立刻开始分享赚钱吧!!",U("/Article/index/")."?cid=".C("CATE_ID"));
       }else{
       $this->redirect('index/index');        
       }
    }
    
    
    //短信接口
    public function sms()
       {  
          //die(json_encode(array("code"=>0)));
          if(!IS_AJAX){
             die('404');
          }
          $apikey = SMSAPIKEY; //请用自己的apikey代替
          $mobile = I('post.mobile'); //请用自己的手机号代替
          $num=cookie("end_sms_num")+1;
          if($num >=SMS_NUM){
             $error=array(
                'code'=>1,
                'detail'=>"请求达到限制!请明天在试!{$num}"
                );
             die(json_encode($error));
          }
          cookie("end_sms_num",$num,3600*SMS_TIME);
          $smsqm= SMSQM;
          $code= getNum(4);
          cookie("code",$code);
          cookie("sms_user_tel",$mobile);
          $tpl_value="#code#=".$code."&#company#=".$smsqm;
          $data=$this->tpl_send_sms($apikey,TPL_ID,$tpl_value,$mobile);
          die($data);
       }


   
    /**
    * 智能匹配模版接口发短信
    * apikey 为云片分配的apikey
    * text 为短信内容
    * mobile 为接受短信的手机号
    */
    private function send_sms($apikey, $text, $mobile){
        $url="http://yunpian.com/v1/sms/send.json";
        $encoded_text = urlencode("$text");
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&text=$encoded_text&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }


    /**
    * 模板接口发短信
    * apikey 为云片分配的apikey
    * tpl_id 为模板id
    * tpl_value 为模板值
    * mobile 为接受短信的手机号
    */
    private function tpl_send_sms($apikey, $tpl_id, $tpl_value, $mobile){
        $url="http://yunpian.com/v1/sms/tpl_send.json";
        $encoded_tpl_value = urlencode("$tpl_value");  //tpl_value需整体转义
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }


    /**
    * url 为服务的url地址
    * query 为请求串
    */
    private function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }

    
    //找回密码
    public function RetakePassword()
    {
        $this->display();
    }

    //找回密码处理
    public function password_s()
    {   
        $ajax=(int)I('get.ajax');
        $data=I("post.");
        $rules = array(
          array('user_tel','require','手机号码必须填写.'),  
          array('user_tel','/^1[3|4|5|7|8][0-9]\d{8}$/','手机号码错误.','0','regex',1),
          array('code','require','验证码必须填写.'),
          array('password','require','密码必须填写.'),
        );
        $user = M("user"); // 实例化User对象 // 手动进行令牌验证 
        if (!$user->validate($rules)->create()){
            $this->error($user->getError());
        }
        if($data['code']!==cookie("code") || $data['user_tel']!==cookie("sms_user_tel")){
            $this->error("验证码不正确!");
        }
        $_user=M('user')->field('id')->where(array('user_tel'=>$data['user_tel']))->find();
        if(!$_user){
           $this->error("账号不存在.");  
        }
        $_data["password"]=md5($data["password"]);
        if($uid=$user->where(array('id'=>$_user['id']))->save($_data)!==false){ 
             $this->success("恭喜您!修改成功!",U('Login/index'));
        }else{ 
             $this->error("修改失败!请联系管理员...");
        }
    }


    
    //空操作
    public function _empty()
    {
        $this->error("系统错误!");
    }
}
